<?php defined('SYSPATH') or die('No direct script access.');

class Model_ReviewParser_Irecommend extends Model_ReviewParser_Abstract
{
    protected $irecommend_url = 'http://www.irecommend.ru';         // Урл IRecommend =)
    //protected $search_url  = '/?x=45&y=15&search_text=';      	// Шаблон урла поиска
    protected $model = null;                                        // Экземпляр модели
    
    public function parse(Model_Model $model)
    {
        $this->model = $model;
        
        // По уже составленному списку урлов парсим
        $url = $model->irecommend_url;
		$this->reviews_url = trim($url);
        while ($page_data = $this->_get_page_data()) {
            //usleep(700000);
			//sleep(5);			
            while ($review_data = $this->_get_review_data($page_data, $link)) {
				usleep(700000);
                $id              = $this->_get_id($review_data);
				$user_nick       = $this->_get_user_nick($review_data);
				$user_link       = $this->_get_user_link($review_data);
                $date            = $this->_get_date($review_data);
                $rating          = $this->_get_rating($review_data);
                
                $pluses          = $this->_get_pluses($review_data);
                $minuses         = $this->_get_minuses($review_data);
                $text            = $this->_get_text($review_data);
                $u               = $this->_get_usefulness($review_data);
				
				$images			 = $this->_get_images($review_data);
                
                ORM::factory('review_irecommend')->add_review($this->model, $id, $text, $pluses, $minuses, $rating,
                    $user_nick, $user_link, $link, $date, $u['yes'], $u['no'], $images);
                
                /*echo 'id - '.$id.'<br />';
                echo 'user_nick - '.$user_nick.'<br />';
                echo 'user_link - '.$user_link.'<br />'; 
                echo 'date - '.date('d-M-y', $date).'<br />'; 
                echo 'rating - '.$rating.'<br />'; 
                echo 'link - '.$link.'<br />'; 
                echo 'pluses - '.$pluses.'<br />'; 
                echo 'minuses - '.$minuses.'<br />'; 
                echo 'text - '.$text.'<br />'; 
                echo 'usefulness - <br />';
                print_r($u);
				echo '<br />images - <br />';
                print_r($images);				
                echo '<hr />';   */
            }  
        }  
    }
    
    /*public function get_reviews_urls($model)
    {
        $urls = array();
        $model_name = trim(str_replace(array('2Gb', '4Gb', '8Gb', '16Gb', '32Gb'), '', $model->name));
        $data = $this->_get_source_code($this->search_url . urlencode($model_name));
        $data = $this->_cut_str('<table class=catproduct>', '</table>', $data); 
        while ($product = $this->_cut_str('<tr>', '</tr>', $data)) {
            $url  = $this->otzovik_url . $this->_cut_str('<a href=', '>', $product);            
            $name = strip_tags($this->_cut_str('<td class=nprods>', '</td>', $product));
            if (strstr(Model_Main::get_clean_name($name), Model_Main::get_clean_name($model_name)) !== false) {
                $urls[] = $url;
                echo '<span style="color: red;">' . $name . '</span> - ' . $url . '<br />';   
            }
        }                                 
        return $urls;
    } 
    
    protected function _get_reviews_urls($url)
    {
        $urls = array();
        $this->reviews_url = $url;
        while ($page_data = $this->_get_page_data()) {
            //usleep(700000);
			sleep(5);
            while ($url = $this->_get_next_review_url($page_data)) {
                $urls[] = $url;    
            }    
        }
        return $urls;
    }     */
    
    protected function _get_page_data()
    {
        if (!$this->reviews_url) {
            return null;
        }
        
        $data = $this->_get_source_code($this->reviews_url); 
               
        // пихаем в $this->reviews_url адрес следущей страницы
        $this->reviews_url = $this->_get_next_page_url($data);
        
        return $data;
    }
    
    protected function _get_next_page_url($data)
    {
        if ($url = $this->_cut_str('<li class="pager-next"><a href="', '" ', $data)) {
            return $this->irecommend_url . $url;      
        }     
        return null;    
    }
	
	protected function _get_review_data(&$data, &$link)
    {
        if ($_data = $this->_cut_str('<li class="item">', '</li>', $data)) {
			if ($url = $this->_cut_str('<h2><a href="', '">', $_data)) {
				$url = $this->irecommend_url . $url;
				$link = $url;
				return $this->_get_source_code($url);
			}   
        }
        return null;
    }
    
    /*protected function _get_next_review_url(&$data)
    {
        if ($url = $this->_cut_str('<h3>', '</h3>', $data)) {
            if ($url = $this->_cut_str('<a href=', '>', $url)) {
                return $this->otzovik_url . $url; 
            }   
        }
        return null;   
    }*/
    
    protected function _get_id($data)
    {
        if ($id = $this->_cut_str('<!-- /#node-myreview-', ' -->', $data)) {
            return (int)$id;    
        }
        return null;
    }
    
    protected function _get_user_nick($data)
    {
        if ($nick = $this->_cut_str('<strong class="reviewer">', '</strong>', $data)) {
			if ($nick = $this->_cut_str('">', '</a>', $nick)) {
				return trim($nick);
			}   
        }
        return null;
    }
    
    protected function _get_user_link($data)
    {
        if ($link = $this->_cut_str('<strong class="reviewer"><a href="', '" title', $data)) {
            return $this->irecommend_url . $link;  
        }
        return null;
    }
    
    protected function _get_date($data)
    {       
		$months = array(
            'Январь'    => '01',
            'Февраль'   => '02',
            'Март'      => '03',
            'Апрель'    => '04',
            'Май'       => '05',
            'Июнь'      => '06',
            'Июль'      => '07',
            'Август'    => '08',
            'Сентябрь'  => '09',
            'Октябрь'   => '10',
            'Ноябрь'    => '11',
            'Декабрь'   => '12',
        );
	
        if ($date = trim($this->_cut_str('<div class="com-date">Опубликовано ', '<br />', $data))) {
			//27 Октябрь, 2012 - 23:04
			$parts = explode(' ', $date);
			$result = array();
			
			$result['d'] = $parts[0];
			$result['m'] = $months[str_replace(',', '', $parts[1])];
			$result['y'] = $parts[2];
			
			$date = strtotime(implode('-', $result));
			if ($date) {
				return $date;
			}       
        }
        return null;
    }
    
    protected function _get_rating($data)
    { 
        while ($count = $this->_cut_str('<span class="on rating">', '</span', $data)) { 
			return (int)$count;
        }
        return 0; 
    }
    
    protected function _get_pluses(&$data)
    {
        if ($pluses = $this->_cut_str('<div class="plus"><b>Достоинства: </b>', '</div', $data)) {
            return trim($pluses);    
        }
        return null;  
    }
    
    protected function _get_minuses(&$data)
    {
        if ($minuses = $this->_cut_str('<div class="minus"><b>Недостатки: </b>', '</div', $data)) {
            return trim($minuses);    
        }
        return null;  
    }
    
    protected function _get_text($data)
    {
        if ($text = $this->_cut_str('<span class="description">', '</span><div class="clear">', $data)) {
            return trim(strip_tags($text));    
        }
        return null;   
    }
    
    
    protected function _get_usefulness($data)
    {
        $usefulness = array();
        $usefulness['yes'] = 0;
        if ($yes = $this->_cut_str('<b class="plus">+', '</b', $data)) {
			$usefulness['yes'] = (int)trim($yes);          
        }
		$usefulness['no'] = 0;
        if ($no = $this->_cut_str('<b class="minus">-', '</b', $data)) {
			$usefulness['no'] = (int)trim($no);          
        }
        return $usefulness;
    }
	
	protected function _get_images($data)
	{
		$images = array();
		if ($data = $this->_cut_str('<fieldset class="fieldgroup group-images">', '</fieldset>', $data)) {
			while ($image = $this->_cut_str('href="', '" ', $data)) {
				$images[] = $image;
			}
        }
        return $images;
	}
}